package io.github.veigara.tcp.framework;


import io.github.veigara.tcp.framework.event.DeviceEventBus;
import io.github.veigara.tcp.framework.factory.DeviceComponentFactory;
import io.github.veigara.tcp.framework.factory.DeviceComponentFactoryRegistry;
import io.github.veigara.tcp.framework.metrics.DeviceMetricsCollector;
import io.github.veigara.tcp.framework.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;


/**
 * 设备接入框架主类
 */
@Component
public class DeviceAccessFramework {
    private static final Logger logger = LoggerFactory.getLogger(DeviceAccessFramework.class);

    private final Map<Integer, DeviceServer> deviceServers = new HashMap<>();
    private final DeviceComponentFactoryRegistry factoryRegistry;
    private final DeviceEventBus eventBus;
    private final DeviceMetricsCollector metricsCollector;

    @Autowired
    public DeviceAccessFramework(
            DeviceComponentFactoryRegistry factoryRegistry,
            DeviceEventBus eventBus,
            DeviceMetricsCollector metricsCollector) {
        this.factoryRegistry = factoryRegistry;
        this.eventBus = eventBus;
        this.metricsCollector = metricsCollector;
    }

    @PreDestroy
    public void destroy() {
        // 停止所有服务器
        stopAllServers();
    }

    // 注册设备服务器
    public void registerDeviceServer(DeviceType deviceType, int  port, NettyConfig nettyConfig, LengthDecodeConfig lengthDecodeConfig) {
        DeviceComponentFactory factory = factoryRegistry.getFactory(deviceType);

        DeviceServerConfig serverConfig = new DeviceServerConfig(
                port,
                deviceType,
                factory.createDecoder().getClass(),
                factory.createEncoder().getClass(),
                nettyConfig,
                lengthDecodeConfig
        );
        DeviceServer server = new DeviceServer(serverConfig, factoryRegistry, eventBus, metricsCollector);
        deviceServers.put(port, server);
        logger.info("Registered device server on port {} for {}", port, deviceType);
    }

    // 启动服务器
    public void startServer(int port) {
        DeviceServer server = deviceServers.get(port);
        if (server != null) {
            server.start();
        } else {
            logger.error("Server not found on port {}", port);
        }
    }

    // 停止服务器
    public void stopServer(int port) {
        DeviceServer server = deviceServers.get(port);
        if (server != null) {
            server.stop();
        } else {
            logger.error("Server not found on port {}", port);
        }
    }

    // 启动所有服务器
    public void startAllServers() {
        deviceServers.values().forEach(DeviceServer::start);
    }

    // 停止所有服务器
    public void stopAllServers() {
        deviceServers.values().forEach(DeviceServer::stop);
    }

    // 获取设备连接
    public Optional<DeviceConnection> getDeviceConnection(String deviceId) {
        return deviceServers.values().stream()
                .map(server -> server.getDeviceConnection(deviceId))
                .filter(Objects::nonNull)
                .findFirst();
    }
}




